package com.employee.attendance_daka.controller;

import com.employee.attendance_daka.common.ResponseResult;
import com.employee.attendance_daka.domain.User;
import com.employee.attendance_daka.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * UserController 是处理用户相关操作的控制器，主要负责用户的登录请求。
 * 通过与 {@link UserService} 的交互来实现具体的业务逻辑。
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 处理用户登录请求。
     *
     * @param user
     * @return 包含登录结果的Map对象
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user){
        //参数校验
        if(user.getUsername() == null || user.getUsername().isEmpty() || user.getPassword() == null || user.getPassword().isEmpty()){
            return ResponseResult.error(400, "用户名和密码不能为空");
        }
        //业务处理
        String result = userService.login(user.getUsername(), user.getPassword());
        try {
            if(result.equals("登录成功")){
                return ResponseResult.success(result);
            }else {
                return ResponseResult.error(400, result);
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "服务器内部错误");
        }
    }

    @PutMapping("/register")
    public ResponseResult register(@RequestBody User user){
        if(user.getUsername() == null || user.getUsername().isEmpty() || user.getPassword() == null || user.getPassword().isEmpty() || user.getEmail() == null || user.getEmail().isEmpty()){
            return ResponseResult.error(400, "用户名、密码和邮箱不能为空");
        }
        //业务处理
        String result = userService.register(user.getUsername(), user.getPassword(), user.getEmail());
        try {
            if(result.equals("注册成功")){
                return ResponseResult.success(result);
            }else {
                return ResponseResult.error(400, result);
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "服务器内部错误");
        }
    }
}